package com.itmiaojie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itmiaojie.mapper.ArticleMapper;
import com.itmiaojie.pojo.Article;
import com.itmiaojie.pojo.Category;
import com.itmiaojie.pojo.ResponseResult;
import com.itmiaojie.pojo.vo.CategoryPageVo;
import com.itmiaojie.pojo.vo.CategoryVo;
import com.itmiaojie.service.CategoryService;
import com.itmiaojie.mapper.CategoryMapper;
import com.itmiaojie.utils.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *
 */
@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{

    @Autowired
    private ArticleMapper articleMapper;
    @Override
    public ResponseResult getCategoryList() {
        //查询文章表  状态为已发布的文章
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus,0);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        //获取文章的分类id，并且去重
        Set<Long> set = new HashSet<>();
        for (Article article : articles) {
            Long id = article.getCategoryId();
            set.add(id);
        }
        for (Long aLong : set) {
            log.info(aLong.toString());
        }
        //根据id查询分类
        List<Category> categories = baseMapper.selectBatchIds(set);
        //查看status 是否为禁用 进行过滤
        for (Category category : categories) {
            System.out.println(category.getStatus());
            if (!category.getStatus().equals("0")){
                categories.remove(category);
            }
        }
        log.info(categories.toString());
        List<CategoryVo> categoryVos = null;
        try {
            categoryVos = BeanCopyUtils.copyBeanList(categories, CategoryVo.class);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return ResponseResult.okResult(categoryVos);
    }

    @Override
    public ResponseResult pageList(Integer pageNum, Integer pageSize, String name, String status) {
        IPage<Category> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasText(name),Category::getName,name);
        queryWrapper.eq(StringUtils.hasText(status),Category::getStatus,status);
        page(page,queryWrapper);
        return ResponseResult.okResult(new CategoryPageVo(page.getRecords(),page.getTotal()));
    }


}




